<template>
  <div class="role-list-container">
    <el-dialog title="添加权限信息" v-model="setRoleDialogVisible" :before-close="closePopUp" width="50%">
      <div class="top-bar">
        <el-input class="search-input" placeholder="请输入编号/中文名/英文名" v-model="searchRole" clearable></el-input>
        <el-button type="primary" plain @click="searchRoleHandle">搜索</el-button>
        <el-button type="primary" plain size="medium" @click="selectTypeRole=1;noSettingRole()">未拥有权限<span class="select-ti" v-show="selectTypeRole === 1"></span></el-button>
        <el-button type="primary" plain size="medium" @click="selectTypeRole=2;getUserRole()">已拥有权限<span class="select-ti" v-show="selectTypeRole === 2"></span></el-button>
      </div>

      <Loading :status="tableLoading">
          <div class="content">
            <el-table :data="tableData" border style="width: 100%;" max-height="350" stripe>
              <el-table-column type="index" label="序号" width="100"> </el-table-column>
              <template v-for="(configItem) in rightTableConfig">
                <el-table-column v-if="configItem['formatter'] && !configItem['formatter']" :label="configItem.title" :width="configItem['width'] ? configItem.width : 'auto'">
                  <template #default="scope">
                    <div>{{ handlerTableArr(configItem.formatter, scope.row[configItem.key]) }}</div>
                  </template>
                </el-table-column>
                <el-table-column v-else-if="configItem['select'] && selectTypeRole === 1" :label="configItem.title" :width="configItem['width'] ? configItem.width : 'auto'">
                  <template #default="scope">
                    <el-select v-model="scope.row[configItem.key]" placeholder="请选择" size="medium">
                      <el-option
                        v-for="(item,index) in configItem['select']"
                        :key="item.index"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column v-else-if="configItem['formatter'] && selectTypeRole === 2" :label="configItem.title" :width="configItem['width'] ? configItem.width : 'auto'">
                  <template #default="scope">
                    {{handlerTableArr(configItem.formatter, scope.row[configItem.key])}}
                  </template>
                </el-table-column>
                <el-table-column v-else :prop="configItem.key" :label="configItem.title" :width="configItem['width'] ? configItem.width : 'auto'">
                </el-table-column>
              </template>
              <el-table-column fixed="right" label="操作" :width="140">
                <template #default="scope">
                  <el-button v-if="selectTypeRole === 1" :icon="Edit" type="danger" size="mini" @click="setRoletoUser(scope.row)">授权</el-button>
                  <el-button v-if="selectTypeRole === 2" :icon="Delete" type="primary" size="mini" @click="cancleRole(scope.row)">取消授权</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <div class="deliver"></div>
          </div>
      </Loading>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closePopUp" size="medium">取 消</el-button>
        <el-button type="primary" size="medium" click="setRightComfirm">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Loading from './Loading.vue'
import axios from 'axios'
import { Edit, Delete } from '@element-plus/icons-vue'
import zlApi from '../../packages/zlDemo/toolApi.js'
export default {
  props: ['setRoleDialogVisible', 'curUser', 'rightTableConfig', 'reqConfig'],
  components: {
    Loading
  },
  data() {
    return {
      Edit: Edit,
      Delete: Delete,
      tableData: [], // 表格数据
      curPageNum: 1, // 当前页码
      pageSize: 999, // 当前页码大小
      listTotal: 10, // 表格数据总数
      curRole: null, // 当前操作的角色数据
      searchRole: '', // 查询角色输入框数据，
      tableLoading: false, // 表格加载状态
      searchKeyWord: '', // 点击查询按钮后保存的查询结果
      selectTypeRole: 1, // 获取的数据类型
      arrowSetRole: [{
        value: true,
        label: '是'
      }, {
        value: false,
        label: '否'
      }],
      userInfo: {
        token: '7215561688b260f6d564d5662e16d40d47b653e38c6426fac96a5a69c5d7aec4',
        userId: 'test1',
        name: '测试',
        idType: '2'
      }
    }
  },
  computed: {
  },
  watch: {
    setRoleDialogVisible(v) {
      if (v) {
        this.noSettingRole()
      } else {
        this.selectTypeRole = 1
      }
    }
  },
  methods: {
    // 处理表格数组
    handlerTableArr(arr, key) {
      console.log(arr, key)
      if (key === undefined || key === null) {
        return ''
      }
      let temp = arr.find(item => {
        return item.key === key
      })
      return temp ? temp.value : ''
    },
    // 获取角色列表请求
    getRoleList() {
      this.tableLoading = true
      var timer = setTimeout(() => {
        this.tableLoading = false
        this.$message.error('暂无数据');
      }, 10000)
      let params = {
        pageNum: this.curPageNum,
        pageSize: this.pageSize
      }
      axios.get('http://localhost:3000/yun/manage/role/getRoles', {
        params: params
      }).then(res => {
        if (res.data.status === 0) {
          this.$message.success('获取角色列表成功')
          this.tableData = res.data.data
          this.listTotal = res.data.total
        } else {
          this.$message.error('获取角色列表失败')
        }
        this.tableLoading = false
        clearTimeout(timer)
      })
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.searchOrGetRole()
    },
    handleCurrentChange(val) {
      this.searchOrGetRole()
    },
    /**
     * 查询或者获取全部角色
     * @param {Boolean} flag true为查询，false为获取全部角色
     * */
    searchOrGetRole() {
      if (this.searchKeyWord !== '') {
        this.tableLoading = true
        var timer = setTimeout(() => {
          this.tableLoading = false
        }, 10000)
        let reqParam = this.reqConfig.searchRight.extendData.req
        let params = {
          pageNum: this.curPageNum,
          pageSize: this.pageSize,
          ...zlApi.handlerReqParams(reqParam, {searchKey: {searchKeyWord: this.searchKeyWord}})
        }
        let protocol = this.reqConfig.searchRight.extendData.protocol
        axios[protocol](this.reqConfig.searchRight.extendData.address, {
          params: params
        }).then(res => {
          if (res.data.status === 0) {
            this.$message.success('查询角色列表成功')
            // this.tableData = res.data.data
            // this.listTotal = res.data.total
            let response = this.reqConfig.searchRight.extendData.res
            let temp = res
            response.data.split('.').map(item => {
              temp = temp[item]
            })
            this.tableData = temp
            temp = res
            response.total.split('.').map(item => {
              temp = temp[item]
            })
            this.listTotal = temp
          } else {
            this.$message.error('查询角色列表失败')
          }
          this.tableLoading = false
          clearTimeout(timer)
        })
      } else {
        this.getRoleList()
      }
    },
    /**
     * 查询角色
     * */
    searchRoleHandle() {
      this.curPageNum = 1
      this.searchKeyWord = this.searchRole
      this.searchOrGetRole()
    },
    /**
     * 关闭弹窗
     * */
    closePopUp() {
      this.$emit('closePopUp')
    },
    /**
     * 授予角色给用户
     * @param {Object} rowData 操作行数据
     * */
    setRoletoUser(rowData) {
      console.log(rowData, this.curUser)
      let reqParam = this.reqConfig.confirmSetRight.extendData.req
      let params = {
        ...zlApi.handlerReqParams(reqParam, {rowData: rowData, curUser: this.curUser, userInfo: this.userInfo})
      }
      let protocol = this.reqConfig.confirmSetRight.extendData.protocol
      console.log(params)
      axios[protocol](this.reqConfig.confirmSetRight.extendData.address, params).then(res => {
        if (res.data.status === 0) {
          this.$message.success('角色授权成功')
        } else {
          this.$message.error('角色授权失败')
        }
        this.noSettingRole()
      })
    },
    /**
     * 取消授权
     * */
    cancleRole(rowData) {
      let reqParam = this.reqConfig.cancelSetRight.extendData.req
      let params = {
        ...zlApi.handlerReqParams(reqParam, {rowData: rowData})
      }
      let protocol = this.reqConfig.cancelSetRight.extendData.protocol
      axios[protocol](this.reqConfig.cancelSetRight.extendData.address, {
        params: params
      }).then(res => {
        if (res.data.status === 0) {
          this.$message.success('撤销角色授权成功')
        } else {
          this.$message.error('撤销角色授权失败')
        }
        this.getUserRole()
      })
    },
    /**
     * 批量授权
     * */
    setRightComfirm() {
      console.log('批量授权')
    },
    /**
     * 查看用户拥有的角色
     * */
    getUserRole() {
      this.tableLoading = true
      var timer = setTimeout(() => {
        this.tableLoading = false
      }, 10000)
      let reqParam = this.reqConfig.setRightList.extendData.req
      let params = {
        pageNum: this.curPageNum,
        pageSize: this.pageSize,
        ...zlApi.handlerReqParams(reqParam, {curUser: this.curUser})
      }
      let protocol = this.reqConfig.setRightList.extendData.protocol
      axios[protocol](this.reqConfig.setRightList.extendData.address, {
        params: params
      }).then(res => {
        if (res.data.status === 0) {
          // this.tableData = res.data.data
          let response = this.reqConfig.searchRight.extendData.res
          let temp = res
          response.data.split('.').map(item => {
            temp = temp[item]
          })
          this.tableData = temp
          temp = res
          response.total.split('.').map(item => {
            temp = temp[item]
          })
        } else {
          this.tableData = []
        }
        this.tableLoading = false
        clearTimeout(timer)
      })
    },
    /**
     * 查看用户未拥有的角色
     * */
    noSettingRole() {
      this.tableLoading = true
      var timer = setTimeout(() => {
        this.tableLoading = false
      }, 10000)
      let reqParam = this.reqConfig.unSetRightList.extendData.req
      let params = {
        ...zlApi.handlerReqParams(reqParam, {curUser: this.curUser})
      }
      let protocol = this.reqConfig.unSetRightList.extendData.protocol
      axios[protocol](this.reqConfig.unSetRightList.extendData.address, {
        params: params
      }).then(res => {
        if (res.data.status === 0) {
          // this.tableData = res.data.data
          let response = this.reqConfig.searchRight.extendData.res
          let temp = res
          response.data.split('.').map(item => {
            temp = temp[item]
          })
          this.tableData = temp
          temp = res
          response.total.split('.').map(item => {
            temp = temp[item]
          })
          this.tableData.map(item => {
            item.rightFlag = false
          })
        } else {
          this.tableData = []
        }
        this.tableLoading = false
        clearTimeout(timer)
      })
    }
  },
  mounted() {
    // this.noSettingRole()
  }
}
</script>

<style scoped lang="less">
  .role-list-container {
    .top-bar {
      margin: 15px 15px 15px 0;
      .search-input {
        width: 300px;
        margin-right: 20px;
      }
    }
    .content {
      height: 350px;
      overflow-y: hidden;
      background: #fff;
      padding-bottom: 8px;
    }
    /deep/.el-table th {
        text-align: center;
    }
    /deep/.el-table td {
        text-align: center;
    }
    /deep/.el-dialog__body {
      padding: 10px 20px;
    }
    /deep/.el-dialog__body {
      padding-top: 0;
    }
  }
</style>
